<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option label="前台" value="1" />
          <el-option label="后台" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="应用" prop="appCode">
        <el-select v-model="queryParams.appCode" placeholder="应用" filterable clearable style="width: 100%">
          <el-option
            v-for="item in productList"
            :key="item.value"
            :label="item.name"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="文件类型" prop="fileType">
        <el-select v-model="queryParams.fileType" placeholder="请选择文件类型" clearable size="small">
          <el-option v-for="(item, index) in fileTypeList" :key="item.value" :label="item.name"
              :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="原文件名" prop="originalName">
        <el-input
          v-model="queryParams.originalName"
          placeholder="请输入原文件名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:oss:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="deleteFile"
          v-hasPermi="['system:oss:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ossList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="对象存储主键" align="center" prop="ossId" /> -->
      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
            <div v-if="scope.row.type=='1'">前台</div>
            <div v-if="scope.row.type=='2'">后台</div>
        </template>
      </el-table-column>
      <el-table-column label="应用" align="center" prop="appName" />
      <el-table-column label="文件类型" align="center" prop="fileTypeName" />
      <el-table-column label="文件名" align="center" prop="fileName" />
      <el-table-column label="原文件名" align="center" prop="originalName" />
      <el-table-column label="文件后缀名" align="center" prop="fileSuffix" />
      <el-table-column label="URL地址" align="center" prop="url" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="deleteFile(scope.row)"
            v-hasPermi="['system:oss:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="存储位置" prop="saveType">
          <el-select v-model="form.saveType" placeholder="请选择类型" clearable size="small">
            <el-option label="OSS" value="1" />
            <el-option label="服务器" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" clearable size="small">
            <el-option label="前台" value="1" />
            <el-option label="后台" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="应用" prop="appCode">
          <el-select v-model="form.appCode" placeholder="应用" filterable clearable>
            <el-option
              v-for="item in productList"
              :key="item.value"
              :label="item.name"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="文件类型" prop="fileType">
          <el-select v-model="form.fileType" placeholder="请选择文件类型" clearable size="small">
            <el-option v-for="(item, index) in fileTypeList" :key="item.value" :label="item.name"
                :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="文件" prop="url">
          <div class="upload-file">
            <el-upload
              :action="uploadFileUrl"
              :before-upload="handleBeforeUpload"
              :file-list="fileList"
              :data = "form"
              :limit="limit"
              :on-error="handleUploadError"
              :on-exceed="handleExceed"
              :on-success="handleUploadSuccess"
              :show-file-list="false"
              :headers="headers"
              class="upload-file-uploader"
              ref="upload"
            >
              <!-- 上传按钮 -->
              <el-button size="mini" type="primary">选取文件</el-button>
            </el-upload>
            <!-- 文件列表 -->
            <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
              <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
                <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
                  <span class="el-icon-document"> {{ file.name }} </span>
                </el-link>
                <div class="ele-upload-list__item-content-action">
                  <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
                </div>
              </li>
            </transition-group>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOss, getOss, delOss, addOss, updateOss, exportOss } from "@/api/system/oss";
import { getAllAppList } from '@/api/configs/appConfig';
import { getToken } from "@/utils/auth";

export default {
  name: "Oss",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API_URL,
      uploadFileUrl: process.env.VUE_APP_BASE_API_URL + "/system/oss/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileTypeList : [{"name":"图文","value":1},{"name":"音频","value":2},{"name":"网页","value":3},{"name":"apk","value":4},{"name":"协议文件","value":5}],
      fileList: [],
      productList:[],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // OSS对象存储表格数据
      ossList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        appCode: null,
        fileType: null,
        fileName: null,
        originalName: null,
        fileSuffix: null,
        url: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        saveType: [
          { required: true, message: "存储类型不能为空", trigger: "change" }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
        appCode: [
          { required: true, message: "应用不能为空", trigger: "change" }
        ],
        fileType: [
          { required: true, message: "文件类型不能为空", trigger: "change" }
        ],
        multipartFile: [
          { required: true, message: "文件不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  created() {
    this.getAppList();
    this.getList();
  },
  methods: {
    //查询应用列表
    getAppList(){
      getAllAppList().then(response => {
        this.productList = response.data.map(item => {
          return {
            id: item.id,
            name: item.appname,
            value: item.appcode
          }
        })
      })
    },
    /** 查询OSS对象存储列表 */
    getList() {
      this.loading = true;
      listOss(this.queryParams).then(response => {
        this.ossList = response.rows;
        this.ossList.forEach(oss=>{
          this.productList.forEach(product=>{
            if(oss.appCode===product.value){
              oss.appName = product.name;
            }
          })
          this.fileTypeList.forEach(type=>{
            if(oss.fileType === type.value.toString()){
              oss.fileTypeName = type.name;
            }
          })
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ossId: null,
        type: null,
        appCode: null,
        fileType: null,
        fileName: null,
        originalName: null,
        fileSuffix: null,
        url: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ossId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加OSS对象存储";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ossId = row.ossId || this.ids
      getOss(ossId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改OSS对象存储";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ossId != null) {
            updateOss(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.fileList = [];
            });
          } else {
            addOss(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.fileList = [];
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    deleteFile(row) {
      const ossIds = row.ossId || this.ids;
      this.$modal.confirm('是否确认删除OSS对象存储编号为"' + ossIds + '"的数据项？').then(function() {
        return delOss(ossIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 上传前校检
    handleBeforeUpload(file) {
      if(!this.form.type || !this.form.appCode || !this.form.fileType){
        this.$message.error(`必填参数未填写!`);
        return false;
      }
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.$message.success("上传成功");
      this.form.fileName = res.data.fileName;
      this.form.originalName = res.data.originalfileName;
      this.form.fileSuffix = res.data.suffix;
      this.form.url = res.data.url;
      this.fileList.push({ name: res.data.originalfileName, url: res.data.url });
      this.$emit("input", this.listToString(this.fileList));
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    }
  }
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
